# -*- coding: utf-8 -*-
import json
import math
import copy
from pyquery import PyQuery
from zc_core.util.http_util import *
from datetime import datetime
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_timestamp
from zc_core.model.items import Catalog, ItemData, Sku, OrderItem, ItemGroup, ItemDataSupply
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.encrypt_util import double_base64_encode, base64_decode, short_uuid, md5

# 解析catalog列表
def parse_catalog(response):
    cats = list()
    json_data = json.loads(response.text).get("data", [])
    for data1 in json_data:
        cat1_id = data1.get('categoryguid')
        cat1_name = data1.get('categoryname')
        cat11 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat11)
        for data2 in data1.get('categoryList', []):
            cat2_id = data2.get('categoryguid')
            cat2_name = data2.get('categoryname')
            cat22 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat22)
            for data3 in data2.get('categoryList', []):
                cat3_id = data3.get('categoryguid')
                cat3_name = data3.get('categoryname')
                cat33 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat33)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0
    return cat


# 解析sku列表页数
def parse_sku_total_page(response):
    json_data = json.loads(response.text)
    totals = json_data.get('data', {}).get('total')
    return totals


# 解析经销商商品页
def parse_full_total_page(response):
    json_data = json.loads(response.text)
    totals = json_data.get('data', {}).get('total')
    return totals


# 解析订单成交页数
def parse_order_total_page(response):
    json_data = json.loads(response.text)
    totals = json_data.get('data', {}).get('total')
    return totals


# 维度：品牌，解析sku列表页数
def parse_brand_total_page(response):
    page_json = json.loads(response.text)
    total_page = page_json['result']['pageTotal']
    return total_page


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog3Id = meta.get('catalog3Id')
    json_data = json.loads(response.text).get('data', {}).get('datamap', {}).get('list', [])
    skus = list()
    items = list()
    catalog_helper = CatalogHelper()
    for data in json_data:
        sku = Sku()
        goods = data.get('goods', {})
        sku['skuId'] = data.get('goodspriceguid')
        sku['catalog3Id'] = catalog3Id
        catalog_helper.fill(sku)
        sku['skuName'] = goods.get('name')
        sku['skuCode'] = data.get('goodscode')
        # sku['unit'] = goods.get('unit')
        sku['batchNo'] = batch_no
        supplier_name = goods.get("suppliername", None)
        if supplier_name:
            sku['supplierName'] = supplier_name
        # sku['supplierSkuLink'] = goods.get('supplierlink')
        sku['supplierId'] = goods.get('supplierguid')
        sku['skuImg'] = goods.get('picturepath')
        sku['brandName'] = goods.get('goodsbrandname')
        sku['brandId'] = goods.get('goodsbrandguid')
        sku['originPrice'] = goods.get('marketprice')
        sku['salePrice'] = goods.get('salesprice')
        sku['soldCount'] = data.get('sellcount')
        sku['brandModel'] = goods.get('code')
        skus.append(sku)

        item = ItemData()
        item.update(copy.deepcopy(sku))
        items.append(item)
    return skus, items


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    sku = meta.get('sku')
    sku_id = sku.get('_id')
    sku['skuId'] = sku_id
    json_data = json.loads(response.text).get('data', {}).get('sameTypeGoodsList', [])
    for data in json_data:
        item = copy.deepcopy(sku)
        result = ItemData()
        result.update(item)
        sku_id = data.get('goodsquotepriceguid')
        result['skuId'] = sku_id
        sale_price = data.get('goodsquotepricemoney')
        result['salePrice'] = sale_price
        origin_price = sale_price
        result['originPrice'] = origin_price
        result['supplierName'] = data.get('suppliername')
        result['supplierId'] = data.get('supplierguid')
        yield result


# 解析商品详情中的supplier信息
def parse_item_supplier(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    json_data = json.loads(response.text).get('data', {}).get('supplierInfo', {})
    result = ItemDataSupply()
    result['skuId'] = sku_id
    result['batchNo'] = batch_no
    result['supplierId'] = json_data.get('supplierguid')
    result['supplierName'] = json_data.get('suppliername')
    return result


# 处理电子卖场同款商品，同类商品
def parse_group(response):
    meta = response.meta
    sku_id = meta.get('skuId')

    same_goods_list = json.loads(response.text).get('data', {}).get('sameTypeGoodsList', [])
    done_set = set()
    done_set.add(sku_id)
    group_list = list()
    group = ItemGroup()
    for data in same_goods_list:
        sku_id = data.get('goods', {}).get('goodsguid')
        group_list.append(sku_id)
        done_set.add(sku_id)
    # 同款（含自身）
    if group_list and len(group_list):
        group['skuId'] = meta.get('skuId')
        group['spuId'] = short_uuid()
        group['skuIdList'] = group_list
    return group, done_set


# 解析订单
def parse_order_item(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    json_data = json.loads(response.text).get('data', {}).get('data', [])
    for data in json_data:
        order = OrderItem()
        order['skuId'] = str(data.get('goodspriceguid'))
        order['count'] = data.get('qty')
        order['amount'] = data.get('agreementtotal')
        order['supplierId'] = str(data.get('supplierguid'))
        order['supplierName'] = data.get('suppliername')
        orderTime = parse_timestamp(data.get('createdate'))
        order['orderTime'] = orderTime
        order['batchNo'] = time_to_batch_no(orderTime)
        order['genTime'] = datetime.utcnow()
        order['deptId'] = data.get('orgguid')
        order['orderDept'] = data.get('orgname')
        order['id'] = data.get('ordercode')
        order['orderId'] = data.get('orderguid')
        yield order
